<script src="{{ getAssets }}js/amazeui.datatables.min.js?v={{ assets_version }}"></script>
<script src="{{ getAssets }}lodop/LodopFuncs.js?v={{ assets_version }}"></script>
<script src="{{ getAssets }}lodop/print_presc.js?v={{ assets_version }}"></script>
<script>
    $('#dateline').datepicker({format: 'yyyy-mm-dd'}).datepicker('setValue', getNowFormatDate());
    var opt_id = 0;
    var tables = $('#dataTables').DataTable({
        "sAjaxSource" : '{{ urlfor "PrescController.Index"}}'
        ,"fnServerData" : function(sSource, aoData, fnCallback) {
            var params = checkQueryTableData(aoData)
            $('#search_key').val() ? params.Filter = $('#search_key').val() : '';
            if($('#dateline').val()) {
                params.startdate = $('#dateline').val();
            }
            params.enddate =  params.startdate;
            $.post(sSource, JSON.stringify(params),function(resp) {
                fnCallback(resp);
            },'json')
        }
        ,columns: [
            {"bSortable": false, render:function(data, type, full, meta) {
                    return full.archives.Realname;
                }}
            ,{"bSortable": false, render:function(data, type, full, meta) {
                    return full.archives.Sex;
                }}
            ,{"bSortable": false, render:function(data, type, full, meta) {
                    return full.archives.Age;
                }}
            ,{"mDataProp": "created_at", render:function(data, type, full, meta) {
                    return timetrans(data);
                }}
            ,{"mDataProp": "status", "bSortable": false, render:function(data, type, full, meta) {
                    switch (data) {
                        case 0:
                            return '<span>待接诊</span>';
                            break;
                        case 1:
                            return '<span class="am-text-secondary">已接诊</span>';
                            break;
                        case 2:
                            return '<span class="am-text-danger">已退号</span>';
                            break;
                    }
                    return '';
                }}
        ]
        ,"aLengthMenu":[100]
        ,'bLengthChange': false
        ,"serverSide": true
        ,"bPaginate" : false
        ,"bFilter" : false	//是否启动过滤、搜索功能
        ,"bInfo" : false //是否显示页脚信息，DataTables插件左下角显示记录数
        ,"bProcessing" : true //DataTables载入数据时，是否显示‘进度’提示
    });
    var groupColumn = 1;
    var dataTablesDoctorOrder = $('#dataTablesDoctorOrder').DataTable({
        order:[]
        ,columns: [
            {"mDataProp" : "status", "bSortable": false, "render":function (data, type, full, meta) {
                    var xu = '';
                    var pay = '';
                    switch (parseInt(full.pay_status)) {
                        case 0:pay ='未支付';break;
                        case 1:pay ='已支付';break;
                        case 2:pay ='待退费';break;
                        case 3:pay ='已退费';break;
                    }
                    switch (parseInt(data)) {
                        case 0:xu ='<span>待发送</span> ';break;
                        case 1:xu ='<span class="am-text-secondary">已发送('+ pay +')</span> ';break;
                        case 2:xu ='<span class="am-text-warning">已回退('+ pay +')</span> ';break;
                        case 3:xu ='<span class="am-text-danger">已退费('+ pay +')</span>';break;
                        case 4:xu ='<span style="color: gray">已作废('+ pay +')</span>';break;
                    }

                    return '<span class="number" style="white-space:nowrap;" data-index="'+ meta.row +'" data-number="'+ full.number.id +'" data-prescdate="'+ timetransDate(full.number.created_at) +'">'+xu+'</span><input type="hidden" class="project_type" value="'+ full.project_type +'"><input type="hidden" class="total_price" value="'+ full.total_price +'">';
            }},
            {"visible": false, "mDataProp" : "number.id","bSortable": false, "render":function (data, type, full, meta) {
                    return '<span >'+ full.number.id +'</span>';
            }},
            {"mDataProp" : "content", "bSortable": false, "render":function (data, type, full, meta) {
                return '<span class="content">'+ data +'</span>';
            }},
            {"mDataProp" : "dosage_zl", "bSortable": false,"render":function (data, type, full, meta) {
                return '<span class="dosage_zl">'+ data +'</span>';
            }},
            {"mDataProp" : "unit", "bSortable": false,"render":function (data, type, full, meta) {
                return '<span class="unit">'+ data +'</span>';
            }},
            {"bSortable": false, render:function(data, type, full, meta) {
                 return '<span class="usage">'+(full.position ? full.position +'，':'')+ showUsageFormat(full.usage_tj, full.usage_pc, full.dosage_ts)+'</span>';
            }},
            {"mDataProp" : "entrust", "bSortable": false},
            {"mDataProp" : "usage_md", "bSortable": false},
            {"mDataProp" : "doctor_name", "bSortable": false,"render":function (data, type, full, meta) {
                return '<span class="doctor_name">'+ data +'</span>';
            }},
            {"mDataProp" : "created_at", "bSortable": false,"render":function (data, type, full, meta) {
                    return '<span class="created_at">'+ timetrans(data) +'</span>';
            }},
            {
                "mDataProp": "Action",
                "bSortable": false,
                "sWidth":"8%",
                "render": function ( data, type, full, meta ) {
                    var btn = [];
                    btn.push('<div class="am-dropdown am-dropdown-up" data-am-dropdown>');
                    btn.push('<button class="am-btn am-btn-danger am-dropdown-toggle am-btn-xs" data-am-dropdown-toggle>操作<span class="am-icon-caret-down"></span></button>');
                    btn.push('<ul class="am-dropdown-content">');
                    if(full.status==1&&full.pay_status==0) {
                        btn.push('<li><a href="javascript:;" onclick="presc_action(1, this);return false;" data-id="'+ full.id +'" data-title="医嘱回退">医嘱回退</a></li>');
                    }
                    if(full.status==2&&full.pay_status==0) {
                        btn.push('<li><a href="javascript:;" onclick="presc_action(4, this);return false;" data-id="'+ full.id +'" data-title="重新发送">重新发送</a></li>');
                    }
                    if(full.pay_status==1) {
                        //btn.push('<li><a href="javascript:;" onclick="presc_action(2, this);return false;" data-id="'+ full.id +'" data-title="医嘱退费">医嘱退费</a></li>');
                    }
                    if(full.status==1&&full.pay_status==0) {
                        btn.push('<li><a href="javascript:;" onclick="presc_action(3, this);return false;" data-id="'+ full.id +'" data-title="医嘱作废">医嘱作废</a></li>');
                    }
                    btn.push('</ul></div>');
                    return btn.join('');
                }
            }
        ]
        ,'bLengthChange': false
        ,"serverSide": false
        ,"bPaginate" : false
        ,"bFilter" : false
        ,"bInfo" : false
        ,"bProcessing" : false
        ,"drawCallback": function ( settings ) {
            var api = this.api();
            //获取当前页的所有行数据
            var rows = api.rows({page:'current'} ).nodes();
            var last=null;
            //遍历行的每一列
            api.column(groupColumn, {page:'current'} ).data().each( function ( group, i ) {
                if ( last !== group ) {
                    $(rows).eq( i ).before(
                        '<tr class="group"><td colspan="12" style="background-color: #1074ff;color:#FFF;">处方编号：'+group+'</td></tr>'
                    );
                    last = group;
                }
            });
            $('.am-dropdown').dropdown();
        }
    });

    $("#searchsubmit").bind("click", function () { //点击按钮 触发table重新请求服务器
        $("#dataTables").dataTable().fnDraw(false);
    });

    $(window).keydown(function (event) {
        if(event.keyCode==13){
            var value = $('#search_key').val();
            if(value != '') {
                $("#searchsubmit").click();
            }
        }
    });
    var sel_member; //选择的患者
    //待诊列表tr点击
    $('#dataTables tbody').on( 'click','tr',function(){
        var data = tables.row(this).data();
        $('#dataTables tbody').find('tr').removeClass('am-active');
        $(this).addClass('am-active');

        if(data.archives) {
            var uinfo = data.archives ;
            var main_obj = $('.userinfo');
            main_obj.find('.name').html(uinfo.Realname);
            main_obj.find('.sex').html(uinfo.Sex);
            main_obj.find('.age').html(uinfo.Age+'岁');
            main_obj.find('.mobile').html(uinfo.Mobile);
            main_obj.find('.birthday').html(uinfo.Birthday);
        }
        sel_member = data;
        doctorOrderQuery();
    });
    //处方列表tr点击
    $('#dataTablesDoctorOrder tbody').on('click','tr',function(){
        if($(this).hasClass('group')) {
            return false;
        }
        var data = dataTablesDoctorOrder.row(this).data();
        $('#dataTablesDoctorOrder tbody').find('tr').removeClass('am-active');
        $(this).addClass('am-active');
        if($(this).find('input[value="drug"]').length > 0) {
            $('#print_chufang').attr('disabled', false);
            $('#print_inspects').attr('disabled', true);
        } else {
            $('#print_chufang').attr('disabled', true);
            $('#print_inspects').attr('disabled', false);
        }

    });

    function addNewPresc() {
        if(!sel_member) {
            layer.msg('请选择患者');return false;
        }
        var url = '{{ urlfor "PrescController.Prescription"}}';
        var index = layer.open({
            type: 2,
            title: '新开处方',
            shadeClose: false,
            shade: 0.2,
            maxmin: false,
            shift: 1,
            area: ['680px', '320px'],
            content: url
        });
        layer.full(index);
    }
    function presc_callback() {
        $("#dataTables").dataTable().fnDraw(false);
        doctorOrderQuery();
    }
    //医嘱操作
    function presc_action(act_type, tar) {
        var title = $(tar).data('title');
        if(confirm('确定要执行“'+ title +'”该操作吗？')) {
            var id = $(tar).data('id');
            $.post('{{ urlfor "PrescController.DoctorOrderAction" }}', {'act_type':act_type, 'id':id}, function (res) {
                if(res.code == 1) {
                    layer.alert(res.msg);return false;
                }
                doctorOrderQuery();  //重新查询处方
            });
        }
        $('.am-dropdown').dropdown('close');
    }
    //打印处方
    $('#print_chufang').click(function(){
        if(!sel_member) {
            layer.msg('请选择患者');return false;
        }
        var index = $('#dataTablesDoctorOrder tbody').find('.am-active').find('.number').data('index');
        var contrast = dataTablesDoctorOrder.row(index).data();

        //获取诊断
        $.post('{{ urlfor "PrescController.Diagnosis" }}',{'guahao_id':sel_member.id, 'archives_id':sel_member.archives.Id}, function (res1) {
            var diagnosis = '';
            if(res1.code == 0)  {
                diagnosis = res1.data.content;
            }
            print_chufang(sel_member.archives, $('#dataTablesDoctorOrder'), contrast, diagnosis);
        },'json');
        return false;
    });
    //打印检查单
    $('#print_inspects').click(function(){
        if(!sel_member) {
            layer.msg('请选择患者');return false;
        }
        var index = $('#dataTablesDoctorOrder tbody').find('.am-active').find('.number').data('index');
        var contrast = dataTablesDoctorOrder.row(index).data();
        print_inspects(sel_member.archives, $('#dataTablesDoctorOrder'), contrast);
        return false;
    });

    //查询处方列表
    function doctorOrderQuery() {
        if(!sel_member) {
            return false;
        }
        $.post('{{urlfor "PrescController.DoctorOrderQuery"}}',JSON.stringify({'guahao_id':sel_member.id,'archives_id':sel_member.archives.Id}), function(res){
            if(res.code == 1) {
                return false;
            }
            var dt = $('#dataTablesDoctorOrder').DataTable();
            dt.clear().draw();
            $.each(res.data, function (index, value) {
                dt.row.add(value).draw();
            });
        }, 'json');
    }

    function slimscroll() {
        var height = $(window).height();
        $('#dataTables_box').slimscroll({
            height: (height-260)+'px',
            width: '100%', //可滚动区域宽度
            size:"10px",
            color:'#0e90d2',
            railVisible: false, //是否 显示轨道
            alwaysVisible: true,
        });
    }
    $(window).resize(function(){
        slimscroll();
    });
    slimscroll();
    function getNowFormatDate() {
        var date = new Date();
        var seperator1 = "-";
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = year + seperator1 + month + seperator1 + strDate;
        return currentdate;
    }
</script>